<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogTitle"
    :close-on-click-modal="false"
    class="device-state-log-dialog"
    width="800px"
  >
    <div class="log-content">
      <el-table
        :data="logData"
        style="width: 100%"
        :empty-text="t('device.stateLogs.noData')"
      >
        <el-table-column prop="bigType" :label="t('device.stateLogs.bigType')" width="120" />
        <el-table-column prop="type" :label="t('device.stateLogs.type')" width="120" />
        <el-table-column prop="value" :label="t('device.stateLogs.value')" />
        <el-table-column prop="status" :label="t('device.stateLogs.status')" width="100">
          <template #default="scope">
            {{ getStatusText(scope.row.status) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" :label="t('device.stateLogs.createdAt')" width="180" />
      </el-table>

    </div>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { getDeviceStateLogApi } from '@/api/products/device';

const props = defineProps<{
  deviceNo?: string;
  visible?: boolean;
}>();

const emit = defineEmits<{
  'update:visible': [value: boolean];
}>();

const { t } = useI18n();
const logData = ref<any[]>([]);
const dialogVisible = computed({
  get: () => props.visible || false,
  set: (val) => {
    emit('update:visible', val);
    if (!val) {
      logData.value = [];
    }
  }
});

const dialogTitle = computed(() => `${t('device.stateLogs.title')} - ${props.deviceNo}`);

const getDeviceStateLogs = async () => {
  logData.value = []
  if (!props.deviceNo) return;
  console.log(props.deviceNo);
  try {
    const response = await getDeviceStateLogApi({
      deviceNo: props.deviceNo
    });
    if(response.code == 0 && response.data &&  response.data.list) {
      logData.value = response.data.list || [];
    }
  } catch (error) {
    console.error('Failed to fetch device state logs:', error);
    logData.value = [];
  }
};

const getStatusText = (status: string): string => {
  const statusMap: Record<string, string> = {
    'success': t('device.stateLogs.statusText.success'),
    'failed': t('device.stateLogs.statusText.failed'),
    'processing': t('device.stateLogs.statusText.processing')
  };
  return statusMap[status] || status;
};

// 监听对话框显示状态，当变为可见时加载数据
watch(
  () => props.visible,
  (isVisible) => {
    if (isVisible && props.deviceNo) {
      getDeviceStateLogs();
    }
  }
);

// 监听设备编号变化，当编号改变时重新加载数据
watch(
  () => props.deviceNo,
  (deviceNo) => {
    if (deviceNo && props.visible) {
      getDeviceStateLogs();
    }
  }
);

</script>

<style scoped>
.device-state-log-dialog {
  .log-content {
    max-height: 500px;
    overflow-y: auto;
  }

  .no-data {
    text-align: center;
    padding: 40px 0;
    color: #909399;
  }
}
</style>

